const express = require('express');
const path = require('path');
const cors = require('cors');
require('dotenv').config();

const { initDatabase } = require('./config/database');
const stockRoutes = require('./routes/stockRoutes');
const Stock = require('./models/stock');
const StockService = require('./services/stockService');

// 创建Express应用
const app = express();
const port = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

// 设置视图引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// API路由
app.use('/api', stockRoutes);

// 页面路由
app.get('/', (req, res) => {
  res.render('index');
});

// 股票详情页面
app.get('/stock/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { page = 1, limit = 20, startDate, endDate } = req.query;
    
    // 获取股票列表
    const stocks = await Stock.getAllStocks();
    console.log('stocks', stocks)
    const stock = stocks.find(s => s.id == id);
    
    if (!stock) {
      return res.status(404).send('股票不存在');
    }
    
    // 获取最新价格
    const latestPrice = await Stock.getLatestPrice(id);
    
    if (!latestPrice) {
      return res.status(404).send('价格数据不存在');
    }
    
    // 计算分页参数
    const pageNum = parseInt(page, 10);
    const pageSize = parseInt(limit, 10);
    const offset = (pageNum - 1) * pageSize;
    
    // 获取价格历史
    const priceHistoryResult = await Stock.getPriceHistory(id, {
      limit: pageSize,
      offset: offset,
      startDate: startDate,
      endDate: endDate
    });
    
    // 获取所有价格历史数据用于计算统计信息
    const allPriceHistory = await Stock.getPriceHistory(id, {
      startDate: startDate,
      endDate: endDate
    });
    
    // 计算最高涨幅和最高跌幅
    let maxGain = 0;
    let maxLoss = 0;
    
    allPriceHistory.data.forEach(price => {
      if (price.close_price && price.open_price) {
        const change = ((parseFloat(price.close_price) - parseFloat(price.open_price)) / parseFloat(price.open_price) * 100);
        if (change > maxGain) {
          maxGain = change;
        }
        if (change < maxLoss) {
          maxLoss = change;
        }
      }
    });
    
    // 计算分页信息
    const totalPages = Math.ceil(priceHistoryResult.total / pageSize);
    
    res.render('stock-detail', {
      stock,
      latestPrice,
      priceHistory: priceHistoryResult.data,
      statistics: {
        maxGain: maxGain.toFixed(2),
        maxLoss: maxLoss.toFixed(2)
      },
      pagination: {
        currentPage: pageNum,
        totalPages: totalPages,
        pageSize: pageSize,
        total: priceHistoryResult.total,
        startDate: startDate || '',
        endDate: endDate || ''
      }
    });
  } catch (error) {
    console.error('渲染股票详情页面失败:', error);
    res.status(500).send('服务器错误');
  }
});

// 等待函数 - 用于延迟执行
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 带重试机制的服务启动
async function startServerWithRetry(maxRetries = 5, retryInterval = 10000) {
  let retries = 0;
  
  while (retries < maxRetries) {
    try {
      console.log('开始启动服务器...');
      
      // 初始化数据库 (database.js中已包含重试机制)
      console.log('正在初始化数据库...');
      await initDatabase();
      console.log('数据库初始化成功');
      
      // 启动服务器
      const server = app.listen(port, () => {
        console.log(`服务器已启动，访问 http://localhost:${port}`);
      });
      
      // 添加服务器错误处理
      server.on('error', (error) => {
        console.error('服务器错误:', error);
      });
      
      // 启动股票数据更新服务
      console.log('正在启动股票数据更新服务...');
      const updateInterval = 1000; // 60秒更新一次
      const updateService = StockService.startUpdateService(updateInterval);
      console.log(`股票数据更新服务已启动，更新间隔: ${updateInterval}ms`);
      
      // 添加进程退出时的清理
      process.on('SIGINT', () => {
        console.log('接收到退出信号，正在关闭服务...');
        if (updateService && typeof updateService.stop === 'function') {
          updateService.stop();
        }
        server.close(() => {
          console.log('HTTP服务器已关闭');
          process.exit(0);
        });
      });
      
      // 如果成功启动，跳出循环
      return;
      
    } catch (error) {
      retries++;
      console.error(`启动服务器失败 (${retries}/${maxRetries}):`, error.message);
      
      if (retries >= maxRetries) {
        console.error('达到最大重试次数，无法启动服务器');
        console.error('错误详情:', error.stack);
        process.exit(1);
      }
      
      console.log(`等待 ${retryInterval/1000} 秒后重试...`);
      await wait(retryInterval);
    }
  }
}

// 启动服务器
async function startServer() {
  try {
    await startServerWithRetry();
  } catch (error) {
    console.error('启动服务器失败:', error);
    console.error('错误详情:', error.stack);
    process.exit(1);
  }
}


startServer();